use ggez::graphics::Rect;
use glam::Vec2;
use ggez::{Context, graphics};
use ggez::mint::Point2;

const WIDTH: f32 = 800.0;
const HEIGHT: f32 = 600.0;

pub struct Mover {
    location: Vec2,
    velocity: Vec2,
    acceleration: Vec2
}

impl Mover {
    pub fn new() -> Mover {
        let location = Vec2{x: WIDTH/2.0, y: HEIGHT/2.0};
        let velocity = Vec2{x: 0.0, y: 0.0};
        let acceleration = Vec2 { x: 0.0, y: 0.0 };
        Mover { location, velocity , acceleration}
    }

    pub fn update(&mut self, ctx: &mut Context) -> () {
        let target_point = ctx.mouse.position();
        let target = Vec2{x: target_point.x, y: target_point.y};

        self.acceleration = (target - self.location).normalize()*0.5;
        self.velocity += self.acceleration;
        self.limit(10.0);
        self.location += self.velocity;
    }

    pub fn check_edges(&mut self) -> () {
        if self.location.x > WIDTH { self.location.x = 0.0}
        else if self.location.x < 0.0 {self.location.x = WIDTH}

        if self.location.y > HEIGHT { self.location.y = 0.0}
        else if self.location.y < 0.0 {self.location.y = HEIGHT}
    }

    pub fn display(&self, ctx: &mut Context, canvas : &mut graphics::Canvas) -> () {
        let rectangle = graphics::Mesh::new_rectangle(
            ctx,
            graphics::DrawMode::fill(),
            Rect{x: -10.0, y: -5.0, w: 20.0, h: 10.0},
            graphics::Color::new(0.5, 0.5, 0.5, 1.0),
        ).unwrap();
        canvas.draw(&rectangle, graphics::DrawParam::default().dest(Point2{x: self.location.x, y: self.location.y}).rotation(self.velocity.y.atan2(self.velocity.x)));
        let rectangle = graphics::Mesh::new_rectangle(
            ctx,
            graphics::DrawMode::stroke(2.0),
            Rect{x: -10.0, y: -5.0, w: 20.0, h: 10.0},
            graphics::Color::BLACK,
        ).unwrap();
        canvas.draw(&rectangle, graphics::DrawParam::default().dest(Point2{x: self.location.x, y: self.location.y}).rotation(self.velocity.y.atan2(self.velocity.x)));
    }

    fn limit(&mut self, top_speed: f32) -> () {
        if self.velocity.length() > top_speed {self.velocity = top_speed*self.velocity.normalize()}
    }
}